package com.cfuture08.eweb4j.jdbc;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import com.cfuture08.eweb4j.cache.SingleBeanCache;
import com.cfuture08.eweb4j.orm.dao.config.bean.DAOConfigBean;
import com.cfuture08.util.ReflectUtil;
import com.cfuture08.util.StringUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
/**
 * 连接池管理类
 * @author cfuture.aw
 * @since v1.a.0
 */
public final class ConnectionManager {

	private static ConnectionManager instance;

	private ComboPooledDataSource ds;

	private ConnectionManager() throws Exception {

		ds = new ComboPooledDataSource();
		DAOConfigBean daoBean = (DAOConfigBean) SingleBeanCache.get(DAOConfigBean.class);
		ReflectUtil ru = new ReflectUtil(daoBean);
		String[] names = ru.getFieldsName();
		for (String n : names){
			Method m = ru.getMethod("get"+StringUtil.toUpCaseFirst(n));
			if (m != null){
				Object value = m.invoke(daoBean);
	
				ReflectUtil ru2 = new ReflectUtil(ds);
				Method m2 = ru2.getMethod("set"+StringUtil.toUpCaseFirst(n));
				if (m2 != null){
					Class<?> clazz = m2.getParameterTypes()[0];
					if (clazz.isAssignableFrom(int.class)){
						m2.invoke(ds, Integer.parseInt((String) value));
					}else if (clazz.isAssignableFrom(String.class)){
						m2.invoke(ds, (String)value);
					}else if (clazz.isAssignableFrom(boolean.class)){
						m2.invoke(ds, Boolean.parseBoolean((String)value));
					}else{
						m2.invoke(ds, value);
					}
				}
			}
		}
	}
	
	public static final ConnectionManager getInstance() {
		if (instance == null) {
			try {
				instance = new ConnectionManager();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return instance;
	}

	public synchronized final Connection getConnection() {
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	protected void finalize() throws Throwable {
		DataSources.destroy(ds); // 关闭datasource
		super.finalize();
	}

}
